package com.projeto.web;

import java.io.Serializable;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.projeto.business.controller.CustomerController;
import com.projeto.persistence.Customer;
import com.projeto.persistence.Customer.CustomerType;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;

@ManagedBean
@SessionScoped
public class CustomerBackBean implements Serializable {

    private List<Customer> customerList, filteredCustomerList;
    private Customer selectedCustomer = new Customer();
    @EJB
    CustomerController customerBean;

    public CustomerType[] getCustomerTypeValues() {
        return Customer.CustomerType.values();
    }
     
    public Customer getSelectedCustomer() {
        return selectedCustomer;
    }

    public void setSelectedCustomer(Customer selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    public void addCustomer() {
        selectedCustomer = new Customer();
    }

    public List<Customer> getCustomerList() {
        if (customerList == null) {
            customerList = customerBean.findAllActive();
        }
        return customerList;
    }

    public List<Customer> getFilteredCustomerList() {
        return filteredCustomerList;
    }

    public void setFilteredCustomerList(List<Customer> filteredCustomerList) {
        this.filteredCustomerList = filteredCustomerList;
    }

    public void reset() {
        customerList = customerBean.findAllActive();
        RequestContext.getCurrentInstance().update("customerForm");
        RequestContext.getCurrentInstance().reset("customerDialogForm");
    }
    
    public void removeCustomer()
    {
        try {
            selectedCustomer.setInactive(true);
            customerBean.save(selectedCustomer);
            customerList.remove(selectedCustomer);
            FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_INFO, "Customer " + selectedCustomer.getFirstName() + " Removed!", "Customer removed"));

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocorreu um erro interno", "Customer Not removed"));
        }        
    }
    
    public void saveCustomer() {
        try {
            customerBean.save(selectedCustomer);
            FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_INFO, "Customer " + selectedCustomer.getFirstName() + " Saved!", "Customer saved"));

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocorreu um erro interno", "Customer Not saved"));
        }
    }
}
